<template>
  <el-card>
    <el-form inline class="user-from">
      <el-form-item>
        <el-input placeholder="用户名" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search">查询</el-button>
        <el-button>清空</el-button>
      </el-form-item>
    </el-form>
    <el-button type="primary" @click="AddUser">添加</el-button>
    <el-button type="danger">批量删除</el-button>
    <el-table :data="userList" border class="user-table" v-loading="loading">
      <el-table-column type="selection" width="60" />
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column label="用户名" prop="username" width="200" />
      <el-table-column label="用户昵称" prop="nickName" width="200" />
      <el-table-column label="角色列表" prop="roleName" width="200" />
      <el-table-column label="创建时间" prop="gmtCreate" width="200" />
      <el-table-column label="更新时间" prop="gmtModified" width="200" />
      <el-table-column label="操作" fixed="right" width="200">
        <template v-slot="{ row }">
          <el-button
            size="small"
            type="info"
            :icon="User"
            @click="showAssignRole(row)"
          />
          <el-button size="small" type="warning" :icon="Edit" />
          <el-button size="small" type="danger" :icon="Delete" />
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:currentPage="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 15, 20]"
      layout="prev, pager, next, jumper, ->, sizes, total"
      :total="total"
      @size-change="getUserList"
      @current-change="getUserList"
    />

    <el-dialog v-model="AddUserVisible" title="添加用户">
      <el-form
        label-width="100px"
        ref="userFormRef"
        :model="userFormData"
        :rules="userFormRules"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userFormData.username" />
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickName">
          <el-input v-model="userFormData.nickName" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="userFormData.password" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="AddUserVisible = false">取消</el-button>
          <el-button type="primary" @click="AddUserSubmitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog v-model="assignRoleVisible" title="设置角色">
      <el-form
        label-width="100px"
        ref="assignRoleFormRef"
        :model="assignRoleFormData"
        :rules="assignRoleFormRules"
      >
        <el-form-item label="用户名">
          <el-input v-model="assignRoleFormData.username" disabled />
        </el-form-item>
        <el-form-item label="角色列表" prop="roleId">
          <!-- v-model="assignRoleFormData.checkAll" 收集的是true全选false全不选
          handleCheckAllChange 点击全选切换的回调
          -->
          <el-checkbox
            v-model="assignRoleFormData.checkAll"
            :indeterminate="assignRoleFormData.isIndeterminate"
            @change="handleCheckAllChange"
            >全选</el-checkbox
          >
          <!-- v-model="assignRoleFormData.roleId" 收集的是选中的 
          handleCheckedChange 单选的回调
          -->
          <el-checkbox-group
            v-model="assignRoleFormData.roleId"
            @change="handleCheckedChange"
          >
            <!-- 遍历所有选项 -->
            <el-checkbox
              v-for="role in assignRoleFormData.allRolesList"
              :key="role.id"
              :label="role.id"
              >{{ role.roleName }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="assignRoleVisible = false">取消</el-button>
          <el-button type="primary" @click="assignRoleSubmitForm"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "XUser",
};
</script>

<script lang="ts" setup>
import { onMounted, ref, reactive } from "vue";
import { ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import { Search, User, Edit, Delete } from "@element-plus/icons-vue";
import type {
  UserItem,
  UserList,
  addUserParams,
  RoleList,
} from "@/api/acl/models/userModel";
import {
  getUserListApi,
  AddUserApi,
  getRoleListApi,
  assignRoleApi,
} from "@/api/acl/user";

/************************************获取用户列表功能********************************/
//#region
const currentPage = ref(1);
const pageSize = ref(5);
const total = ref(0);
const userList = ref<UserList>([]);
const username = ref("");
const loading = ref(false);
const getUserList = async () => {
  loading.value = true;
  const res = await getUserListApi({
    page: currentPage.value,
    limit: pageSize.value,
    username: username.value,
  });
  ElMessage.success("获取用户列表成功");
  userList.value = res.items;
  total.value = res.total;
  loading.value = false;
};
onMounted(getUserList);
//#endregion

/***********************************添加用户列表功能**********************************/
//#region
const AddUserVisible = ref(false);
const userFormRef = ref<FormInstance>();
const userFormData = reactive<addUserParams>({
  username: "",
  nickName: "",
  password: "",
});
const userFormRules = reactive<FormRules>({
  username: [{ required: true, message: "请输入SPU描述", trigger: "blur" }],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, message: "请输入6个字以上的密码", trigger: "blur" },
  ],
});

const AddUser = () => {
  AddUserVisible.value = true;
  userFormData.username = "";
  userFormData.nickName = "";
  userFormData.password = "";
  userFormRef.value?.clearValidate();
};

const AddUserSubmitForm = async () => {
  await userFormRef.value?.validate();
  await AddUserApi(userFormData);
  AddUserVisible.value = false;
  ElMessage.success("添加用户成功");
  getUserList();
};
//#endregion

/***********************************分配角色功能*************************************/
const assignRoleVisible = ref(false);
const assignRoleFormRef = ref<FormInstance>();
interface AssignRole {
  username: string;
  checkAll: boolean;
  isIndeterminate: boolean;
  userId: string;
  roleId: string[];
  allRolesList: RoleList;
}
const assignRoleFormData = reactive<AssignRole>({
  username: "", //用户名
  checkAll: false, //全选
  isIndeterminate: false, //半选
  userId: "", //用户id
  roleId: [], //选中的id
  allRolesList: [], //所有选项
});
const assignRoleFormRules = ref<FormRules>({
  roleId: [{ required: true, message: "请输入选择角色", trigger: "blur" }],
});

//分配角色按钮的回调
const showAssignRole = async (row: UserItem) => {
  assignRoleVisible.value = true;
  assignRoleFormData.username = row.username;
  assignRoleFormData.userId = row.id;
  const res = await getRoleListApi(row.id);
  assignRoleFormData.allRolesList = res.allRolesList;
  //得到所选的角色
  assignRoleFormData.roleId = res.assignRoles.map((item) => item.id);
  //判断如果所选中有一个以上而且没有全选 变为半选状态
  assignRoleFormData.isIndeterminate =
    !!assignRoleFormData.roleId.length &&
    assignRoleFormData.roleId.length !== assignRoleFormData.allRolesList.length;
};

//全选
const handleCheckAllChange = (val: string | number | boolean) => {
  //val 为true 全选  为false 全不选
  if (val) {
    //全部角色选中
    assignRoleFormData.roleId = assignRoleFormData.allRolesList.map(
      (item) => item.id
    );
  } else {
    //全部角色不选中
    assignRoleFormData.roleId = [];
  }
  //点击全选框，要隐藏半选框
  assignRoleFormData.isIndeterminate = false;
};

//单个选
const handleCheckedChange = () => {
  assignRoleFormData.isIndeterminate =
    !!assignRoleFormData.roleId.length &&
    assignRoleFormData.roleId.length !== assignRoleFormData.allRolesList.length;
  assignRoleFormData.checkAll =
    assignRoleFormData.roleId.length === assignRoleFormData.allRolesList.length;
};

//提交表单
const assignRoleSubmitForm = async () => {
  await assignRoleFormRef.value?.validate();
  await assignRoleApi(assignRoleFormData.userId, assignRoleFormData.roleId);
  ElMessage.success("分配角色成功");
  assignRoleVisible.value = false;
  getUserList();
};
</script>

<style scoped>
.user-from {
  margin-bottom: 10px;
}
.user-table {
  margin: 30px 0;
}
</style>
